<?php

class ShopController extends Core_Controller_Action 
{
	public $menuType = 1;
	public $itemsLimit = 12;
	private $_products;
	private $_helpSess;
	private $isajax = 'no';
	public $currency = array("pl" => "PLN", "en" => "EUR" , "cs" => "CZK");
	
	public function init() {
		$this->view->menuType = $this->menuType;
		$this->_products = new Products();
		
		$this->_helpSess = new Zend_Session_Namespace( 'form' );
		
		if( !isSet( $this->_helpSess->form ) ) {
			$this->_helpSess->form = array();			
		}
		
		if($this->_request->isXmlHttpRequest())
        {
           
            if($this->_request->getPost('isajax','no')=='yes')
            {
                $ajaxBasket= new Zend_Session_Namespace('ajaxBasket');
                $ajaxBasket->is = "yes";
            }
        }
		
	}

	public function indexAction() {
		
		$_news = new News();
		$_news = $_news->getItemService(17)->getFirst();
		
		if($_news)
		{
			$_news = $_news->toArray();
			
			$this->view->item2 = $_news;
		}
		else
		{
			$this->view->empty = true;
		}
		
		
		
		if( !$this->userData ) {
			$items = $this->_products->getListService( 3, array(
				'r1' => 'yes'
			) );

			$this->view->list = $items;
		} else {
			$sess = new Zend_Session_Namespace( 'ranks' );
			
			if( count( $sess->data ) > 0 ) {
				$items = $this->_products->getListService( 3, false, $sess->data );
			} else {
				$items = $this->_products->getListService( 3, array(
					'r1' => 'yes'
				) );
			}
			$this->view->list = $items;
		}
	}
	
	public function accountAction() {
		
		$this->view->error_pass = intval( $this->_getParam( 'error_pass', 0 ) );
		$this->view->ok_pass = intval( $this->_getParam( 'ok_pass', 0 ) );
		
		if( $this->userData ) {
			$Users = new Users();
			$item = $Users->getItemByIdService( $this->userData->u_id );
			
			if( $this->_request->isPost() ) 
			{
				$post = $this->_request->getPost();

				foreach( $post as $key => $value ) {
					$this->view->{$key} = $value;

					if( !in_array( $key, array(
						'pass', 'email', 'role', 'provision', 'state'
					) ) ) {
						$item->{$key} = $value;
					}
				}	

				$item->save();
				
				// Zapisanie nowych danych do sesji zalogowanego
        	    $storage = new Zend_Auth_Storage_Session;
        	    $data = $storage ->read();
        	    $data->company_name = $post['company_name'];
        	    $data->nip = $post['nip'];
        	    $data->name = $post['name'];
        	    $data->surname = $post['surname'];
        	    $data->phone = $post['phone'];
        	    $data->birthday_day = $post['birthday_day'];
        	    $data->birthday_month = $post['birthday_month'];
        	    $data->birthday_year = $post['birthday_year'];
        	    $data->locality = $post['locality'];
        	    $data->street = $post['street'];
        	    $data->nr_home = $post['nr_home'];
        	    $data->nr_flat = $post['nr_flat'];
        	    $data->zip = $post['zip'];
        	    $data->province = $post['province'];
        	    $data->country = $post['country'];
        	    $storage ->write($data);
        	    
			} 
		
				foreach( $item->toArray() as $key => $value ) 
				{
					$this->view->{$key} = $value;
				}
			
		}
	}
	
	public function ordersAction() {
		
			$Orders = new Orders();
			
			$fav = intval( $this->_getParam( 'fav', 0 ) );
			$proforma = intval( $this->_getParam( 'proforma', 0 ) );
			
			if( $fav ) {
				
				$item = $Orders->getItemService( $fav );
				if( $item = $item->getFirst() ) {
				    
					if( ($item->users_u_id == $this->userData->u_id) && $item->state==1 ) 
					{
						$this->_helper->layout->disableLayout();
						$this->_helper->viewRenderer->setNoRender();
						
						if( $item->vouchers_v_id > 0 ) {
							$this->getResponse()->setHeader( 'Content-type', 'application/pdf' );
							$this->getResponse()->setHeader( 'Content-Disposition', 'attachment; filename="nota_ksiegowa_'.$fav.'.pdf"' );
							readfile( "./public/faktury/bon_".$fav.".pdf" );
						} 
						elseif( $item->vouchers_v_id == 0 ) {
							$this->getResponse()->setHeader( 'Content-type', 'application/pdf' );
							$this->getResponse()->setHeader( 'Content-Disposition', 'attachment; filename="faktura_'.$fav.'_vat.pdf"' );
							readfile( "./public/faktury/faktura_".$fav."_vat.pdf" );
						}
						else
    					{
    					   $this->_redirect( 'shop/index/' );
    					}
					}
					elseif($item->users_u_id == $this->userData->u_id && $proforma==1) 
					{
						$this->_helper->layout->disableLayout();
						$this->_helper->viewRenderer->setNoRender();
						
						$this->getResponse()->setHeader( 'Content-type', 'application/pdf' );
						$this->getResponse()->setHeader( 'Content-Disposition', 'attachment; filename="faktura_'.$fav.'_proforma.pdf"' );
						readfile( "./public/faktury/faktura_".$fav."_proforma.pdf" );
						
					}
					else
					{
					   $this->_redirect( 'shop/index/' );
					}
					
				}
			} else {
			    
			    if($this->userData)
			    {
        				$page = intval( $this->_getParam( 'page', 1 ) );
        				$pager = $Orders->getListWithPagerService( $this->userData->u_id );
        				
        				if( $pager ) {
        					$pagerLayout = $pager['layout'];
        					$pagerLayout->setTemplate('<a class="nums" href="{%url}">{%page}</a>');
        					$pagerLayout->setSelectedTemplate('<a class="nums focus" href="{%url}">{%page}</a>');
        					
        					$pager = $pager['pager'];
        				
        					$this->view->list = $pagerLayout->execute();
        					
        					if( count( $this->view->list ) ) {
        						$this->view->pager = $pagerLayout;
        						$this->view->result = $pager->getNumResults();
        						$this->view->page = $page;
        						$this->view->pathInfo = $this->view->baseUrl() . $this->_request->getPathInfo();
        						$this->view->limit = $this->itemsLimit;
        					} else {
        						$this->view->emptyResult = true;
        					}
        	
        				} else {
        					$this->view->emptyResult = true;
        				} 
			    }
			}
		
	}
	
	public function vouchersAction() {
		if( $this->userData ) {
			$Vouchers = new Vouchers();
			$list = $Vouchers->getListService( $this->userData->u_id );
			if( count( $list ) ) {
				$this->view->list = $list;
			} else {
				$this->view->emptyResult = true;
			}
		}
	}
	
	public function chpassAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();

		if( $this->_request->isPost() ) {
			$post = $this->_request->getPost();
			
			$Users = new Users();
			$item = $Users->getItemByIdService( $this->userData->u_id );
			
			if( $item->pass == md5( $post['actpass'] ) ) {
				if( $post['pass'] == $post['password_retype'] ) {
					$item->pass = md5( $post['pass'] );
					$item->save();
					$this->_redirect( 'shop/account/ok_pass/1' );
				} else {
					$this->_redirect( 'shop/account/error_pass/1' );
				}
			} else {
				$this->_redirect( 'shop/account/error_pass/1' );
			}
		} 
	}
	
	public function deleteAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		$Users = new Users();
		$item = $Users->getItemByIdService( $this->userData->u_id );
		
		$item->state = 1;
		$item->save();
		
    	Zend_Auth::getInstance()->clearIdentity();
    	
    	$sess = new Zend_Session_Namespace( 'ranks' );
    	$sess->unsetAll();
    	
    	$this->_redirect( 'index/index' );
	}
	
	public function basketAction() {
	    
		$add = $this->_request->getParam( 'add', 0 );
		$dem = $this->_request->getParam( 'dem', 0 );
		$newdem = $this->_request->getParam( 'newdem', 0 );
		$delete = $this->_request->getParam( 'delete', 0 );
		$items = $this->_request->getParam( 'items', 1 );
		$plus = $this->_request->getParam( 'plus', 0 );
		$minus = $this->_request->getParam( 'minus', 0 );
		$free = $this->_request->getParam( 'free', 0 );
		$special = $this->_request->getParam( 'special', 0 );
		$code = $this->_request->getParam( 'code', '' );
		$save = $this->_request->getParam( 'save', '1' );
		$observed = intval( $this->_request->getParam( 'observed', 0 ) );
		$this->view->ActionName = $this->_request->getActionName();

		$vou = $this->_request->getPost( 'voucher', '' );
		
		
		
		if($save){
		
		foreach($_POST as $post){
			
			$this->view->echo .= $post.".<br />";
		}
			
		
		}
		if( $this->_request->isPost() && $observed > 0 ) {
			$post = $this->_request->getPost();
			
			foreach( $post['add'] as $value ) {
			    
			    if( $post['stock'][$value]>0)
			    {
			    
				    $this->basket->add( $value, $post['dimension'][$value], $post['stock'][$value], $special );
			    }

			}
			
		//Core_Debug::pr($this->_request->getPost());die();
			$this->_redirect( 'shop/basket/' );
			exit;
		}
		
		if($vou=='yes' && $this->userData  )
		{
		    unset($this->basket->sess->basket['id_vouchers']);
		    unset($this->basket->sess->basket['value_vouchers']);
			    
			//zapisywanie użytych voulcherów
			$post = $this->_request->getPost();
			
			if((isset($post['vouchers'])) && (is_array($post['vouchers'])))
			{
			    //Sa zaznaczone vouchery i kliknieto przelicz
    			$this->basket->sess->basket['id_vouchers'] = $post['vouchers'];
    			$vou = 0;
    			foreach($post['vouchers'] as $one) $vou += $one;
    		
    			$this->basket->sess->basket['value_vouchers'] = $vou;
			}
			else
			{
			    //Vouchere zostaly odznaczone i kliknieto przelicz
			    unset($this->basket->sess->basket['id_vouchers']);
			    unset($this->basket->sess->basket['value_vouchers']);
			}
		}
		
        $this->view->check_vol = array();
        
		if(isset($this->_request->vouchers)) 
		{
		   $this->view->check_vol = $this->_request->vouchers; 
		}
		if(isset($this->basket->sess->basket['id_vouchers']))
		{
		    $this->view->check_vol =  $this->basket->sess->basket['id_vouchers'];
		}
		

		if($code!='')
		{
		    $discount = new Discount();
		    // kod jest dla konkretnego usera ?
		    $kod = $discount->getItemWithUser($this->userData->u_id, $code)->getFirst();
		    if(!$kod)
		    {
		        // kod jest dla wszystkich userow ?
		        $kod = $discount->getItemWithUser(0, $code)->getFirst();
		    }
		    
		    if($kod)
		    {
					if( $kod->used == 'no' ||  is_null($kod->used) || $kod->species=='man' )
					{
						$this->basket->sess->basket['discount'] = $kod->value;
						$this->basket->sess->basket['code_id'] = $kod->di_id;
					}
		    }
		
		    $this->_redirect( 'shop/basket/' );   
		}
		else
		{

		}
		

		
		if( $delete && $dem ) {
			$this->basket->delete( $delete, $dem );
			$this->_redirect( 'shop/basket/' );
			exit;
		}
		
		if( $newdem && $dem ) {
			$this->basket->delete( $add, $dem );
		}
		
		if( $add && $dem && !$plus && !$minus ) {
			
			$dem = ( $newdem > 0 ) ? $newdem : $dem;

			$this->basket->add( $add, $dem, $items, $special );
			$this->_redirect( 'shop/basket/' );
			exit;
			
		} else if( $add && ( $plus || $minus ) ) {
			
			if( $plus ) {
				$this->basket->plus( $add, $free, $plus );
			} else if( $minus ) {
				$this->basket->minus( $add, $free, $minus );
			}
			$this->_redirect( 'shop/basket/' );
			exit;
			
		}	
        
		//onblur na ilosci danego produktusetamount
		$sid = $this->_request->getParam('sid', 0);
		$amount = $this->_request->getParam('setamount', 0);
		
		if($sid>0 && $amount>0)
		{
		    $this->basket->amount($sid, $free, $amount);
		    $this->_redirect( 'shop/basket/' );
		}
		
		 
		if( $this->basket->count < 1 ) 
		{
		    //koszyk jest pusty
		    $this->basket->clear();
			$this->render( 'basketempty' );
		}
		else
		{
		    $this->basket->sumDb(false);
		    
    		if( $this->userData ) {
    			$vou = new Vouchers();
    			$this->view->vouchers = $vou->getList($this->currency[$this->locale], $this->userData->u_id);
    		
    		} else {
    			$this->view->vouchers = false;
    		}
		}
	 
        $ajaxBasket= new Zend_Session_Namespace('ajaxBasket');
                	 
		if($ajaxBasket->is=='yes')
		{
		    $ajaxBasket->is = 'no';
		    $this->_helper->layout->disableLayout();
		}

	}
	

	public function deliveryAction() {

		if( $this->basket->count < 1 ) {
			$this->_redirect( 'shop/index' );
		}

		$fast = intval( $this->_getParam( 'f', 0 ) );
		
		$this->view->fast = $fast;
		$this->view->ActionName = $this->_request->getActionName();
		if( $this->userData ) {
			$userData = $this->userData->toArray();
			
			if( !isSet( $this->_helpSess->formLogged ) ) {						
				$this->_helpSess->formLogged = array();
				$this->_helpSess->formLogged['email'] = $userData['email'];
				$this->_helpSess->formLogged['name'] = $userData['name'];
				$this->_helpSess->formLogged['surname'] = $userData['surname'];
				$this->_helpSess->formLogged['phone'] = $userData['phone'];
				$this->_helpSess->formLogged['locality'] = $userData['locality'];
				$this->_helpSess->formLogged['street'] = $userData['street'];
				$this->_helpSess->formLogged['country'] = $userData['country'];
				$this->_helpSess->formLogged['province'] = $userData['province'];
				
				$this->_helpSess->formLogged['nr_home'] = $userData['nr_home'] . ' ' . $userData['nr_flat'];
				$this->_helpSess->formLogged['zip'] = $userData['zip'];
			}
	
			if( count( $this->_helpSess->formLogged ) ) {
				foreach( $this->_helpSess->formLogged as $key => $value ) {
					$this->view->{$key} = $value;
				}
			}
			
		} else {
			if( count( $this->_helpSess->form ) ) {
				foreach( $this->_helpSess->form as $key => $value ) {
					$this->view->{$key} = $value;
				}
			}
		}

		if( $this->_request->isPost() ) {

			$post = $this->_request->getPost();

			foreach( $post as $key => $value ) {
				$this->_helpSess->formLogged[$key] = $value;
				$this->_helpSess->form[$key] = $value;
				$this->view->{$key} = $value;
			}

			$this->view->nextStep = true;

			$this->view->sess = ( $this->userData ) ? $this->_helpSess->formLogged :  $this->_helpSess->form;

		} else {
			$Facility = new Facility();
			$facility = $Facility->getListService( $this->locale );

			$temp = array();
			foreach( $facility->toArray() as $val ) {
				$temp[$val['f_id']] = $val['city_' . $this->locale ];
			}

			$this->view->facilityList = $temp;
		}
		
		
		//Udostepniamy za pobraniem ?
		$pobranie = true;
		
		if(isset($this->userData->u_id))
		{
    		foreach( $this->basket->sess->basket['items'] as $value ) 
    		{
    			foreach( $value as $elem ) 
    			{
    			    if(isset($elem['info']['manufacturers_m_id']))
    			    {
        			   $manModel = new ManufacturersHasUsers;
        			   $manItem = $manModel->getByManufacturersAndUserId($elem['info']['manufacturers_m_id'], $this->userData->u_id)->getFirst();
        			   
        			   if($manItem)
        			   {
        			       if($manItem['rank_id']>1)
        			       {
        			           $pobranie = false;
        			       }
    		           }
    			    }
    			}
    		}
		}
		

		
		//Jak jest w koszyku jakis produkt specjalny to nie ma za pobraniem
		if($this->basket->isAnySpecialProduct)
		{
		    $pobranie = false;
		}
		
		$this->view->pobranie = $pobranie;
		
		
	}
	
	public function checkoutAction() {
		if( $this->basket->count < 1 ) {
			$this->_redirect( 'shop/index' );
		}
		
		if( $this->_request->isPost() ) {

    	    // sprawdzamy czy na 100% jest zaznaczone tylko karta, przelew online, paypal
    		// jesli w koszyku znajduje sie produkt specjalny lub user jest w randze
    		// cenowej wiekszej niz 1
    		if($this->basket->isAnySpecialProduct || (isset($this->userData->price_rank) && $this->userData->price_rank>1))
    		{
    		   $payment = $this->_request->getPost('payment');
    		   if($payment=='p1' || $payment=='p4')
    		   {
    		       die('Payment Method not allowed');
    		   }
    		}
		 
    	
    	// obsluga kodow rabatowych
		if( isSet($this->basket->sess->basket['code_id']) && $this->basket->sess->basket['code_id']!='' )
		{
		    $code_id = intval($this->basket->sess->basket['code_id']);
		    $discount = new Discount();
		    $kod = $discount->getItem($code_id)->getFirst();
		    
		    if($kod)
		    {
					if( $kod->used == 'no' ||  is_null($kod->used) || $kod->species=='man' )
					{
							$kod->used = 'yes';
							$kod->save();
					}
					else
					{
						$this->basket->sess->basket['discount'] = 0;
						$this->basket->sess->basket['code_id'] = 0;
					}
		    } 
		    else
		    {
		        $this->basket->sess->basket['discount'] = 0;
		    }
		}
			
			$post = $this->_request->getPost();
			
			$Orders = new Orders();
			if( $this->_helpSess->form['fac_ok'] > 0 ) {
				$this->basket->sumDb();
			} else {
				$this->basket->sumDb( true );
			}
			
			$sumAll = number_format( $this->basket->sumInt + $this->basket->deliveryInt, 2, '.', '' );
            
			if(isset($this->basket->sess->basket['value_vouchers']) && $this->basket->sess->basket['value_vouchers']>0)
            {
               $valueAllVouchers = number_format( $this->basket->sess->basket['value_vouchers'], 2, '.', '' ); 
            }
            else
            {
                $valueAllVouchers = 0 ;
            }
            
			$sumAllminusVouchers = number_format($sumAll-$valueAllVouchers, 2, '.', '' );
            
			//sprawdzanie voucherów
			if( $this->userData && isSet( $this->basket->sess->basket['id_vouchers'] ) ) {
				$vou = new Vouchers();
				$vouchers = $vou->getList($this->currency[$this->locale], $this->userData->u_id);
				
				$tab_rzecz_vou = array();
				$caly_upust_vou = 0;
				$tab_sprawdz = $this->basket->sess->basket['id_vouchers'];
				$tab_sprawdz = array_flip($tab_sprawdz);
				foreach($vouchers as $vv)
				{
					if(in_array($vv->v_id, $tab_sprawdz))
						$caly_upust_vou += $vv->value;
					
				}
				if($sumAll>$caly_upust_vou)
				{
					$upust =number_format( $caly_upust_vou, 2, '.', '' );
					//$sumAll -= $caly_upust_vou;
					
					foreach($vouchers as $vv)
					{
				        // Przelatujemy po wszystkich voucherach usera i zerujemy te ktore zostaly
				        // wybrane w formularzu
					    if(in_array($vv->v_id, array_flip($this->basket->sess->basket['id_vouchers'])))
					    {
    						$vv->used_date = Date( 'Y-m-d H:i:s' );
    						$vv->value = 0;
    						$vv->save();
					    }
					}
				}
				else
				{
					$caly_upust_vou = $sumAll;
					//$sumAll = 0;
					$upust = number_format( $caly_upust_vou, 2, '.', '' );
					foreach($vouchers as $vv)
					{
					    if(in_array($vv->v_id, array_flip($this->basket->sess->basket['id_vouchers'])))
					    {
    						if($vv->value<$caly_upust_vou)
    						{
    							$caly_upust_vou -= $vv->value;
    							$vv->used_date = Date( 'Y-m-d H:i:s' );
    							$vv->value = 0;
    							$vv->save();
    						}
    						else
    						{
    							$vv->used_date = Date( 'Y-m-d H:i:s' );
    							$vv->value -=$caly_upust_vou;
    							$vv->save();
    							break;
    						}
					    }
					}
				}
				//koniec sprawdzania voucherów
			}
			
			$Orders->facility_f_id = intval( $this->_helpSess->form['fac_ok'] );
			$Orders->users_u_id = ( $this->userData ) ? $this->userData->u_id : null;
			$Orders->currency = $this->basket->curr;
			$Orders->payment = isSet( $post['payment'] ) ? $post['payment'] : '';
			$Orders->price = $sumAll;
			$Orders->email = $this->_helpSess->form['email'];
			$Orders->state = 0;
			$Orders->state2 = ( $this->userData ) ? 1 : 0;
			$Orders->state3 = 0;
			$Orders->state4 = 0;
			$Orders->state5 = 0;
			$Orders->name_to_dispatch = $this->_helpSess->form['name'];
			$Orders->surname_to_dispatch = $this->_helpSess->form['surname'];
			$Orders->street_to_dispatch =$this->_helpSess->form['street'];
			$Orders->nr_home_to_dispatch = $this->_helpSess->form['nr_home'];
			$Orders->locality_to_dispatch = $this->_helpSess->form['locality'];
			$Orders->zip_to_dispatch = $this->_helpSess->form['zip'];
			$Orders->province_to_dispatch = intval($this->_helpSess->form['province']);
			$Orders->country_to_dispatch = $this->_helpSess->form['country'];
			$Orders->nip_to_fv = $post['fv_nip'];
			$Orders->company_to_fv = $post['fv_company_name'];
			$Orders->name_to_fv = $post['fv_name'];
			$Orders->surname_to_fv = $post['fv_surname'];
			$Orders->street_to_fv = $post['fv_street'];
			$Orders->nr_home_to_fv = $post['fv_nr_home'];
			$Orders->locality_to_fv = $post['fv_locality'];
			$Orders->zip_to_fv = $post['fv_zip'];
			$Orders->province_to_fv = $post['fv_province'];
			$Orders->country_to_fv = $post['fv_country'];
			$Orders->add_date = Date( 'Y-m-d H:i:s' );
			$Orders->vouchers_value = ( isSet( $upust ) ) ? $upust : 0;
			
			$agentProvision = false;
			$sumProvision = 0;
			$sumProvisionClear = 0;
			
			if( $this->userData && $this->userData->parent_u_id ) {
				$Users = new Users();
				$agent = $Users->getItemByIdService( $this->userData->parent_u_id );
				$agentProvision = true;
			}
			$Orders->save();

			if( $Orders->o_id ) {
				$this->view->nr_order = $Orders->o_id;

				$r = '<ul>';
				$r2 = '';
				$lp = 1;
				
				$Query = $Orders->getItemService($this->view->nr_order);
				
				$this->view->payment = $Query->getFirst()->payment;
				$this->view->name = $Query->getFirst()->name_to_dispatch;
				$this->view->surname = $Query->getFirst()->surname_to_dispatch;
				$this->view->email = $Query->getFirst()->email;

				$total['netto'] = 0;
				$total['vat'] = 0;
				$total['brutto'] = 0;
				
				// Wartosc przesylki
				//$shipment['netto'] = 7.62;
				//$shipment['vat'] = 2.14;
				//$shipment['brutto'] = 9.76;
				
				@$shipvatvalue =  ($this->basket->deliveryInt / 100)*22;
				$shipment['netto'] = $this->basket->deliveryInt - $shipvatvalue ;
				@$shipment['vat'] = number_format($shipvatvalue, 2, '.', ' ');
				//$shipment['vat'] = $shipvatvalue;
				$shipment['brutto'] = $this->basket->deliveryInt;
				
				
				if(!isset($this->basket->sess->basket['discount']))
				{
				    $this->basket->sess->basket['discount'] =  0;
				}
				
				foreach( $this->basket->sess->basket['items'] as $value ) {
					foreach( $value as $elem ) {
						$OrdersItems = new OrdersItems();
						//Core_Debug::pr($elem['rank']); die();
						if( !$elem['special'] ) {
							$xy = 0;
							foreach( $elem['info']['Dimension']->toArray() as $vDem ) {
								if( $vDem['d_id'] == $elem['dem'] ) {
									break;
								}
								$xy++;
							}
							
							$price = $elem['info']['Dimension'][$xy]['price' . $elem['rank']];
							$price -= $price * $this->basket->sess->basket['discount'] / 100;
							
							$price = number_format( $price, 2, '.', ' ' );
	
							$Dimension = new Dimension();
							$itemd = $Dimension->getItemService( $elem['dem'] )->getFirst();
							$itemd->stock = $itemd->stock - $elem['cnt'];
							$itemd->save();
						} else {
							$price = $elem['info']['price' . $elem['rank']];
							$price -= $price * $this->basket->sess->basket['discount'] / 100;
							$price = number_format( $price, 2, '.', ' ' );
						}
						
						if( $agentProvision ) {
							$prov = $price * $elem['info']['Manufacturers']->provision / 100;
							$sumProvision = $sumProvision + $prov;
							
							$sumProvisionClear = $sumProvisionClear + $price;
						}
						
						$OrdersItems->orders_i_id = $Orders->o_id;
						$OrdersItems->products_p_id = ( $elem['special'] ) ? $elem['info']['ps_id'] : $elem['info']['p_id'];
						$OrdersItems->items = $elem['cnt'];
						$OrdersItems->special = $elem['special'];
						$OrdersItems->dimension_d_id = $elem['dem'];
						$OrdersItems->save();
						
						$r .= '<li>' . $elem['info']['name_' . $this->locale] . ' ' . $this->view->translate( 'items_order' ) . ': ' . $elem['cnt'] . '</li>';
						
						//$vatOneCnt = round(($price*$elem['info']['Vat']['rate']*0.01), 2);
						//$vatAllCnt = round(($price*$elem['cnt']*$elem['info']['Vat']['rate']*0.01), 2);
						
						// Wartosc podatku VAT dla jednej sztuki danego produktu
						$vatOneCnt = number_format(($price*$elem['info']['Vat']['rate']*0.01), 2, '.', ' ' );
						// Wartosc podatku VAT dla calkowitej ilosci danego produktu
						$vatAllCnt = number_format(($price*$elem['cnt']*$elem['info']['Vat']['rate']*0.01), 2, '.', ' ' );
						// Cena netto danego produktu dla calkowitej ilosci danego produktu 
						$priceCnt = number_format($price*$elem['cnt'], 2, '.', ' ' );
						// Cena brutto danego produktu dla calkowitej ilosci danego produktu
						$totalCntVat = $vatAllCnt+$priceCnt;
						
						$r2 .= '<tr>';
						$r2 .= '<td>'.$elem['info']['name_' . $this->locale].'</td>';
						$r2 .= '<td>'.$elem['cnt'].'</td>'; // Ilosc
						$r2 .= '<td>'.number_format($price, 2, '.', '' ).' '.$this->basket->curr.'</td>'; // Cena za sztuke PLN (netto)
						$r2 .= '<td>'.$elem['info']['Vat']['rate'].'%</td>'; // VAT w %
						$r2 .= '<td>'.number_format(($vatOneCnt+$price), 2, '.', '' ).' '.$this->basket->curr.'</td>'; //Cena za sztuke PLN (brutto)
						$r2 .= '<td>'.@number_format($priceCnt, 2, '.', '' ).' '.$this->basket->curr.'</td>'; //Razem PLN (netto)
						$r2 .= '<td>'.number_format($totalCntVat, 2, '.', '' ).' '.$this->basket->curr.'</td>'; //Razem PLN (brutto)
						$r2 .= '</tr>';

						$total['netto'] = $total['netto'] + ($price*$elem['cnt']);
						$total['vat'] = $total['vat'] + $vatAllCnt;
						$total['brutto'] = $total['brutto'] + $totalCntVat;
						
						$lp++;
					}
				}
				
				if( $agentProvision ) {
					$it = $Orders->getItemService( $Orders->o_id )->getFirst();
					$provTmp = $sumProvisionClear * $agent->provision / 100;
					
					$it->provision = $sumProvision + $provTmp;
					$it->save();
				}
				
				$r .= '</ul>';
				
				$r2 .= '
				
                 <tr>
                 	<td>Koszt przesyłki</td>
                 	<td>1</td>
                 	<td>'.number_format($shipment['netto'], 2, '.', '' ).' '.$this->basket->curr.'</td>
                 	<td>22%</td>
                 	<td>'.number_format(($shipment['netto']+$shipment['vat']), 2, '.', '' ).' '.$this->basket->curr.'</td>
                 	<td>'.number_format($shipment['netto'], 2, '.', '' ).' '.$this->basket->curr.'</td>
                 	<td>'.number_format(($shipment['netto']+$shipment['vat']), 2, '.', '' ).' '.$this->basket->curr.'</td>
                 </tr>
				';
				
				//Dodajemy wartosc przesylki
				$total['netto'] = $total['netto'] + $shipment['netto'];
				$total['vat'] = $total['vat'] + $shipment['vat'];
				$total['brutto'] = $total['brutto'] + $shipment['brutto'];
				
				$total['netto'] = number_format($total['netto'], 2, '.', '' );
				$total['vat'] = number_format($total['vat'], 2, '.', '' );
				$total['brutto'] = number_format($total['brutto'], 2, '.', '' );
				
				
                // **********************************************
                // GLOBALNY STUFF DLA FAKTURY PRO FORMA I ZWYKLEJ
                // **********************************************
                
				
				$paymentmethod_right = '
                          <td style="text-align:right">
                              '.$this->view->translate('order_nazwabanku').': <b>Alior Bank S.A</b><br>
                              '.$this->view->translate('order_nrrachunku').': <b>21 2490 0005 0000 4520 2521 0620</b>
                          </td>';
				
				$paymentmethod = '
                      <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="font-size:12px; width:90%; text-align:left; margin:15px auto 15px auto">
                      <TBODY>
                        <tr>
                           <td>
                              '.$this->view->translate('order_sposobplatnosc').': <b>'.$this->view->translate('order_sposobplatnosc_przelew').'</b><br>
                              '.$this->view->translate('order_terminplatnosci').': <b>14 '.$this->view->translate('order_dni').'</b>
                          </td>
							'.$paymentmethod_right.'
                        </tr>
                      </TBODY>
                      </TABLE>';
				
				// Zostaly uzyte jakies vouchery ?
        		if( (isset($this->basket->sess->basket['id_vouchers'])) && (!empty($this->basket->sess->basket['id_vouchers'])) )
        		{
        		    // Tak - Sa jakies vouchery :Q
        		    
        		    // $sumAll - suma wszystkich zakupowo lacznie z przesylka
        		    $valueAllVouchers;
        		    // $sumAllminusVouchers - suma wszystkich zakupowo lacznie z przesylka minus wartosc wszystkich voucherow
                    // $this->basket->curr - waluta
                    
        		    // Generujemy htmla z nota ksiegowa voucherow
                    $vouhtml = '';
                    foreach($this->basket->sess->basket['id_vouchers'] As $ind => $val)
        		    {
        		        $vouhtml .= '&nbsp;&nbsp;&nbsp;'.$this->view->translate('bon_nr_noty_ksiegowej').': <b>'.date('Y').'/NK/'.$ind.'</b><br>'; 
        		    }

        		    
                    if($sumAllminusVouchers>0)
                    {
                        // Czesc jest zaplacona voucherami ale jeszcze pozostalo do zaplacena przelewem
                        
                        // Dopisujemy wartosc wszystkich uzytych voucherow
        		        $vouhtml .= '&nbsp;&nbsp;&nbsp;'.$this->view->translate('wartosc_bonow').': <b>'.number_format($valueAllVouchers, 2, '.', '' ).' '.$this->basket->curr.'</b>';
                        
        				$paymentmethod = '
                              <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="font-size:12px; width:90%; text-align:left; margin:15px auto 15px auto">
                              <TBODY>
                                <tr>
                                   <td>
                                      '.$this->view->translate('order_sposobplatnosc').':<br>
                                      &nbsp;&nbsp;&nbsp;'.$this->view->translate('order_sposobplatnosc_przelew').': <b>'.$sumAllminusVouchers.' '.$this->basket->curr.'</b><br>
                                      &nbsp;&nbsp;&nbsp;'.$this->view->translate('order_terminplatnosci').': <b>14 '.$this->view->translate('order_dni').'</b><br>
                                      '.$vouhtml.'
                                  </td>
        							'.$paymentmethod_right.'
                                </tr>
                              </TBODY>
                              </TABLE>';
                        
                    }
                    
                    if($sumAllminusVouchers<=0)
                    {
                        // Wszystko zaplacone voucherami
                        
                        // Dopisujemy wartosc wszystkich uzytych voucherow, w tym przypadku wartosc calego zamowienia
        		        $vouhtml .= '&nbsp;&nbsp;&nbsp;'.$this->view->translate('wartosc_bonow').': <b>'.$total['brutto'].' '.$this->basket->curr.'</b>';
                        
        				$paymentmethod = '
                              <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="font-size:12px; width:90%; text-align:left; margin:15px auto 15px auto">
                              <TBODY>
                                <tr>
                                   <td>
                                   	  '.$this->view->translate('order_sposobplatnosc').':<br>
                                      '.$vouhtml.'
                                  </td>
        							'.$paymentmethod_right.'
                                </tr>
                              </TBODY>
                              </TABLE>';
                    }
                    
		                        
        		}
		
                // **************************
                // START FAKTURA - PRO FORMA
                // **************************
                
				
            	$srcLogo = 'public/images/carnaubalogo.jpg';
            	$html['header'] = '
            	
                      <TABLE  cellpadding="0" cellspacing="0" BORDER="0" style="font-size:12px; width:90%; margin:0 auto">
                         <TBODY>
                         <TR>
                            <TD>
                            <img src="'.$srcLogo.'" width="150" height="115">
                            </TD>
                            <TD style="text-align:right">
                            <b>Kraków '.date("d/m/Y").'</b>
                            </TD>
                         </TR>
                      </TBODY>
                      </TABLE>';
            	
                    $html['body'] = '
                    
                    <style type="text/css">
                    body, td {font-family: sans-serif; }
                    .bg1 {background-color:#F3F3F3; font-weight:bold}
                    </style>
                    
                    <body>
            
                      <p style="font-size:20px; width:90%; text-align:left; margin:0 auto">
                      <b>'.$this->view->translate('order_fakturaproforma').' NR '.$this->view->nr_order.'</b><br>
                      </p>
                      
                       <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="font-size:12px; width:90%; text-align:left; margin:15px auto 15px auto">
                         <TBODY>
                         <TR>
                            <TD style="text-align:left; vertical-align:top">
                            <b>'.$this->view->translate('order_sprzedawca').'</b><br>
                    	  	Cars Care Sp. z o.o.<br>
                    	  	ul. Szlak 77/134<br>
                          	31-153 Kraków<br>
                          	Polska<br>
                          	NIP: 676-240-99-08<br>
                            </TD>	

                            <TD style="text-align:right; vertical-align:top">
                            <b>'.$this->view->translate('order_nabywca').'</b><br>
						'.((!empty($post['fv_company_name'])) ? $post['fv_company_name'].'<br>' : '').'
						'.$post['fv_surname'].' '.$post['fv_name'].'<br>
						'.$post['fv_zip'].' '.$post['fv_locality'].'<br>
						ul. '.$post['fv_street'].' '.$post['fv_nr_home'].'<br>
						'.Core_Static::$country[$post['fv_country']].', '.Core_Static::$province[$post['fv_province']].'<br>
						'.((!empty($post['fv_nip'])) ? 'NIP: '.$post['fv_nip'].'<br>' : '').'
                            </TD>
                         </TR>
                      </TBODY>
                      </TABLE>
                    
                      <p style="font-size:12px; width:90%; text-align:left; margin:0 auto">
                      <b>'.$this->view->translate('order_datawystawienia').'</b> '.date("d/m/Y").'
                      </p>
                    
                      <TABLE  cellpadding="3" cellspacing="0" BORDER="1" style="font-size:11px; width:90%; text-align:center; margin:5px auto 5px auto">
                         <TBODY>
                         <TR>
                            <TD class="bg1" style="width:40%">'.$this->view->translate('order_opis').'</TD>
                            <td class="bg1">'.$this->view->translate('order_ilosc').'</td>
                            <TD class="bg1" style="width:12%">'.$this->view->translate('order_sztukanetto').'</TD>
                            <TD class="bg1">'.$this->view->translate('order_procvat').'</TD>
                            <TD class="bg1" style="width:12%">'.$this->view->translate('order_sztukabrutto').'</TD>
                            <TD class="bg1" style="width:12%">'.$this->view->translate('order_rnetto').'</TD>
                            <TD class="bg1" style="width:12%">'.$this->view->translate('order_rbrutto').'</TD>
                         </TR>
                    
					
                         '.$r2.'
                         

                         
                         <tr>
                         <td colspan="5" style="text-align:right"><b>'.$this->view->translate('order_razem').'</b></td>
                         <td><b>'.$total['netto'].' '.$this->basket->curr.'</b></td>
                         <td><b>'.$total['brutto'].' '.$this->basket->curr.'</b></td>
                         </tr>
                         
                      </TBODY></TABLE>
                      
                    
                      <TABLE cellpadding="3" cellspacing="0" BORDER="0" style="font-size:11px; width:90%; margin:5px auto 5px auto">
                      <tr>
                      <td style="width:30%"></td>
                      <td>
                                  <TABLE  cellpadding="3" cellspacing="0" BORDER="1" style="font-size:12px; width:350px; text-align:center; margin:5px auto 5px auto">
                                     <TBODY>
                                     <TR>
                                        <TD class="bg1" style="width:50%; text-align:right">'.$this->view->translate('order_trazemnetto').':</TD>
                                        <TD style="text-align:left"><b>'.$total['netto'].' '.$this->basket->curr.'</b></TD>
                                     </TR>
                                     <TR>
                                        <TD class="bg1" style="text-align:right">'.$this->view->translate('order_tvat').' 22%:</TD>
                                        <TD style="text-align:left"><b>'.$total['vat'].' '.$this->basket->curr.'</b></TD>
                                     </TR>
                                     <TR>
                                        <TD class="bg1" style="text-align:right">'.$this->view->translate('order_trazemvat').':</TD>
                                        <TD style="text-align:left"><b>'.$total['brutto'].' '.$this->basket->curr.'</b></TD>
                                     </TR>
                                  </TBODY>
                                  </TABLE>
                      </td>
                      </tr>
                      </table>

                    
						'.$paymentmethod.'
                    
                    
                      <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="font-size:12px; width:90%; text-align:center; margin:50px auto 15px auto">
                      <TBODY>
                        <tr>
                          <td style="text-align:left"></td>
                          <td style="text-align:right"><b>KAMIL KRAWCZYK</b></td>
                        </tr>
                        <tr>
                          <td style="text-align:left">'.$this->view->translate('order_podpisosobyodbior').'</td>
                          <td style="text-align:right">'.$this->view->translate('order_podpisosobywystawienie').'</td>
                        </tr>
                      </TBODY>
                      </TABLE>
                      
                    </body>';
            	
                    $html['fotter'] = '
            
                      <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="text-align:center; font-size:10px; width:90%; margin:10px auto 15px auto">
                      <TBODY>
                        <tr>
                          <td colspan="3" style="text-align:center; font-size:11px">
                          <br>
                            '.$this->view->translate('order_niniejszydokument').'       
                            <Br><br><br>
                          </td>
                        </tr>
                        <tr>
                          <td style="vertical-align:top">
                            <span style="color:#a50021"><b>'.$this->view->translate('order_renowacja').'  </b></span><br>
                            Cars Care Sp. z o.o.<br>
                            Salon - ul. Balicka 117<br>
                            30-149 Kraków<br>
                          </td>
                          <td style="vertical-align:top">
                            <span style="color:#a50021"><b>'.$this->view->translate('order_pielegnacja').'  </b></span><br>
                            NIP: 676-240-99-08<br>
                            kom +48 501-509-399<br>
                            KRS: 0000345500<br>
                          </td>
                          <td style="vertical-align:top">
                            <span style="color:#a50021"><b>'.$this->view->translate('order_ochrona').'  </b></span><br>
                            www.carnauba.pl<br>
                          </td>
                        </tr>
                      </TBODY>
                      </TABLE>
                      <p style="text-align:right">{PAGENO}</p>';
            	
                require_once("./library/mpdf/mpdf.php");
                $mpdf=new mPDF('utf-8');
                $mpdf->SetHTMLHeader($html['header'], null, true);
                $mpdf->SetHTMLFooter($html['fotter']);
                $mpdf->WriteHTML($html['body']);
                $contentPdfFileProforma = $mpdf->Output('', 'S');
                file_put_contents("./public/faktury/faktura_".$this->view->nr_order."_proforma.pdf", $contentPdfFileProforma);

                
                // **************************
                // START FAKTURA - ZWYKŁA
                // **************************
				
            		$html['header'] = '
            		
                      <TABLE  cellpadding="0" cellspacing="0" BORDER="0" style="font-size:12px; width:90%; margin:0 auto">
                         <TBODY>
                         <TR>
                            <TD>
                            <img src="'.$srcLogo.'" width="150" height="115">
                            </TD>
                            <td>
                            ORYGINAŁ / KOPIA
                            </td>
                            <TD style="text-align:right">
                            <b>'.$this->view->translate('order_datawystawienia').':</b> '.date("d/m/Y").'<br>
                            <b>'.$this->view->translate('order_datasprzedazy').':</b> '.date("d/m/Y").'
                            </TD>
                         </TR>
                      </TBODY>
                      </TABLE>';
            	
                    $html['body'] = '
                    
                    <style type="text/css">
                    body, td {font-family: sans-serif; }
                    .bg1 {background-color:#F3F3F3; font-weight:bold}
                    </style>
                    
                    <body>
            
                      <p style="font-size:20px; width:90%; text-align:left; margin:0 auto">
                      <b>'.$this->view->translate('order_fakturazwykla').' NR '.$this->view->nr_order.'</b><br>
                      </p>
                      
                       <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="font-size:12px; width:90%; text-align:left; margin:15px auto 15px auto">
                         <TBODY>
                         <TR>
                            <TD style="text-align:left; vertical-align:top">
                            <b>'.$this->view->translate('order_sprzedawca').'</b><br>
                    	  	Cars Care Sp. z o.o.<br>
                    	  	ul. Szlak 77/134<br>
                          	31-153 Kraków<br>
                          	Polska<br>
                          	NIP: 676-240-99-08<br>
                            </TD>
                            <TD style="text-align:right; vertical-align:top">
                            <b>'.$this->view->translate('order_nabywca').'</b><br>
						'.((!empty($post['fv_company_name'])) ? $post['fv_company_name'].'<br>' : '').'
						'.$post['fv_surname'].' '.$post['fv_name'].'<br>
						'.$post['fv_zip'].' '.$post['fv_locality'].'<br>
						ul. '.$post['fv_street'].' '.$post['fv_nr_home'].'<br>
						'.Core_Static::$country[$post['fv_country']].', '.Core_Static::$province[$post['province']].'<br>
						'.((!empty($post['fv_nip'])) ? 'NIP: '.$post['fv_nip'].'<br>' : '').'
                            </TD>
                         </TR>
                      </TBODY>
                      </TABLE>
                    
                      <p style="font-size:12px; width:90%; text-align:left; margin:0 auto">
                      <b>'.$this->view->translate('order_datawystawienia').'</b> '.date("d/m/Y").'
                      </p>
                    
                      <TABLE  cellpadding="3" cellspacing="0" BORDER="1" style="font-size:11px; width:90%; text-align:center; margin:5px auto 5px auto">
                         <TBODY>
                         <TR>
                            <TD class="bg1" style="width:40%">'.$this->view->translate('order_opis').'</TD>
                            <td class="bg1">'.$this->view->translate('order_ilosc').'</td>
                            <TD class="bg1" style="width:12%">'.$this->view->translate('order_sztukanetto').'</TD>
                            <TD class="bg1">'.$this->view->translate('order_procvat').'</TD>
                            <TD class="bg1" style="width:12%">'.$this->view->translate('order_sztukabrutto').'</TD>
                            <TD class="bg1" style="width:12%">'.$this->view->translate('order_rnetto').'</TD>
                            <TD class="bg1" style="width:12%">'.$this->view->translate('order_rbrutto').'</TD>
                         </TR>
                    
					
                         '.$r2.'
                         

                         
                         <tr>
                         <td colspan="5" style="text-align:right"><b>'.$this->view->translate('order_razem').'</b></td>
                         <td><b>'.$total['netto'].' '.$this->basket->curr.'</b></td>
                         <td><b>'.$total['brutto'].' '.$this->basket->curr.'</b></td>
                         </tr>
                         
                      </TBODY></TABLE>
                      
                    
                      <TABLE cellpadding="3" cellspacing="0" BORDER="0" style="font-size:11px; width:90%; margin:5px auto 5px auto">
                      <tr>
                      <td style="width:30%"></td>
                      <td>
                                  <TABLE  cellpadding="3" cellspacing="0" BORDER="1" style="font-size:12px; width:350px; text-align:center; margin:5px auto 5px auto">
                                     <TBODY>
                                     <TR>
                                        <TD class="bg1" style="width:50%; text-align:right">'.$this->view->translate('order_trazemnetto').':</TD>
                                        <TD style="text-align:left"><b>'.$total['netto'].' '.$this->basket->curr.'</b></TD>
                                     </TR>
                                     <TR>
                                        <TD class="bg1" style="text-align:right">'.$this->view->translate('order_tvat').' 22%:</TD>
                                        <TD style="text-align:left"><b>'.$total['vat'].' '.$this->basket->curr.'</b></TD>
                                     </TR>
                                     <TR>
                                        <TD class="bg1" style="text-align:right">'.$this->view->translate('order_trazemvat').':</TD>
                                        <TD style="text-align:left"><b>'.$total['brutto'].' '.$this->basket->curr.'</b></TD>
                                     </TR>
                                  </TBODY>
                                  </TABLE>
                      </td>
                      </tr>
                      </table>
                      

                      <TABLE cellpadding="3" cellspacing="0" BORDER="0" style="font-size:11px; width:90%; margin:5px auto 5px auto">
                      <tr>
                      <td style="width:30%"></td>
                      <td>
                                  <TABLE  cellpadding="3" cellspacing="0" BORDER="1" style="font-size:12px; width:350px; text-align:center; margin:5px auto 5px auto">
                                     <TBODY>
                                     <TR>
                                        <TD class="bg1" style="width:50%; text-align:right">'.$this->view->translate('order_dozaplaty').':</TD>
                                        <TD style="text-align:left"><b>'.$total['brutto'].' '.$this->basket->curr.'</b></TD>
                                     </TR>
                                     <TR>
                                        <TD class="bg1" style="text-align:right">'.$this->view->translate('order_zaplacono').':</TD>
                                        <TD style="text-align:left"><b>'.$total['brutto'].' '.$this->basket->curr.'</b></TD>
                                     </TR>
                                     <TR>
                                        <TD class="bg1" style="text-align:right">'.$this->view->translate('order_pozostaje').':</TD>
                                        <TD style="text-align:left"><b>0</b></TD>
                                     </TR>
                                  </TBODY>
                                  </TABLE>
                      </td>
                      </tr>
                      </table>
                    
                    
						'.$paymentmethod.'
                    
                    
                      <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="font-size:12px; width:90%; text-align:center; margin:50px auto 15px auto">
                      <TBODY>
                        <tr>
                          <td style="text-align:left"></td>
                          <td style="text-align:right"><b>KAMIL KRAWCZYK</b></td>
                        </tr>
                        <tr>
                          <td style="text-align:left">'.$this->view->translate('order_podpisosobyodbior').'</td>
                          <td style="text-align:right">'.$this->view->translate('order_podpisosobywystawienie').'</td>
                        </tr>
                      </TBODY>
                      </TABLE>
                      
                    </body>';
            	
                    $html['fotter'] = '
            
                      <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="text-align:center; font-size:10px; width:90%; margin:10px auto 15px auto">
                      <TBODY>
                        <tr>
                          <td style="vertical-align:top">
                            <span style="color:#a50021"><b>'.$this->view->translate('order_renowacja').'  </b></span><br>
                            Cars Care Sp. z o.o.<br>
                            Salon - ul. Balicka 117<br>
                            30-149 Kraków<br>
                          </td>
                          <td style="vertical-align:top">
                            <span style="color:#a50021"><b>'.$this->view->translate('order_pielegnacja').'  </b></span><br>
                            NIP: 676-240-99-08<br>
                            kom +48 501-509-399<br>
                            KRS: 0000345500<br>
                          </td>
                          <td style="vertical-align:top">
                            <span style="color:#a50021"><b>'.$this->view->translate('order_ochrona').'  </b></span><br>
                            www.carnauba.pl<br>
                          </td>
                        </tr>
                      </TBODY>
                      </TABLE>
                      <p style="text-align:right">{PAGENO}</p>';
            	
                $mpdf=new mPDF('utf-8');
                $mpdf->SetHTMLHeader($html['header'], null, true);
                $mpdf->SetHTMLFooter($html['fotter']);
                $mpdf->WriteHTML($html['body']);
                $contentPdfFileVat = $mpdf->Output('', 'S');
                file_put_contents("./public/faktury/faktura_".$this->view->nr_order."_vat.pdf", $contentPdfFileVat);

                
                // **************************
                // KONIEC FAKTURY
                // **************************  
                
                
				if( $this->userData ) {
				
					$mail = new Core_Mail();
					$mail->addTo( $this->_helpSess->form['email'], $this->_helpSess->formLogged['name'] . ' ' . $this->_helpSess->formLogged['surname'] );
					$mail->setFrom( 'no-reply@carnauba.pl', 'Carnauba' );
					$mail->setSubject( $this->view->translate( 'order_topic' ) );
					$mail->setBodyHtml( 
						sprintf( 
							$this->view->translate( 'order_body' ),
							$this->_helpSess->formLogged['name'] . ' ' . $this->_helpSess->formLogged['surname'],
							$r,
							$sumAll . ' ' . $this->basket->curr
						) 
					);

            	    if($post['payment']=='p1' || $post['payment']=='p4')
            	    {
    					$attachment = $mail->createAttachment( $contentPdfFileProforma );
    					$attachment->filename ='fak_'.$this->view->nr_order.'.pdf';
            	    }
            	    
					$mail->send();
					
					$this->view->tr_info = true;
					
				} else {
				    
				    //Zakupu dokonala osoba niezalgoowana
				    
					$url = $this->serverName . $this->view->baseUrl() . '/shop/order/i/' . $Orders->o_id;

					$mail = new Core_Mail();
			
	            	if($post['payment']=='p1' || $post['payment']=='p4')
            	    {
    					$attachment = $mail->createAttachment( $contentPdfFileProforma );
    					$attachment->filename ='fak_'.$this->view->nr_order.'.pdf';
            	    }
					
            	    if($post['payment']=='p2' || $post['payment']=='p3' || $post['payment']=='p5')
            	    {
            	        //platnosc jedna z metod online
            	        $bodyhtml = $this->view->translate( 'confirm_nolink_order_body' );
            	        $this->view->tr_info = true;
            	    }
            	    else
            	    {
            	        //platnosc za pobraniem lub przelew przedplata
            	        $bodyhtml = $this->view->translate( 'confirm_order_body' );
            	        $this->view->tr_confirm_info = true;
            	    }
            	    
            	    $bHtml = sprintf( 
						$bodyhtml,
						$this->_helpSess->form['name'] . ' ' . $this->_helpSess->form['surname'],
						$r,
						$sumAll . ' ' . $this->basket->curr,
						$url,
						$url
					);

					$mail->addTo( $this->_helpSess->form['email'], $this->_helpSess->form['name'] . ' ' . $this->_helpSess->form['surname'] );
					$mail->setFrom( 'no-reply@carnauba.pl', 'Carnauba' );
					$mail->setSubject( $this->view->translate( 'confirm_order_topic' ) );
					$mail->setBodyHtml( 
						$bHtml
					);
					$mail->send();
					
					
				}
			} else {
				$this->view->tr_error = true;
			}
		}

//		unset( $this->_helpSess->formLogged );



	}
	

	
	public function orderAction() {
		$this->view->order_confirm_result = 'order_confirm_result_false';
		$id = intval( $this->_getParam( 'i', 0 ) );

		$Orders = new Orders();
		$item = $Orders->getItemService( $id );
		if( $item = $item->getFirst() ) {
			
			$time = strtotime( $item->add_date . ' + 1 DAY' );
			if( $time > strtotime( 'now' ) ) {
			
				$item->state2 = 1;
				$item->save();
				
				$this->view->order_confirm_result = 'order_confirm_result_true';
			
			}
		}
	}
	
	public function producerAction() {
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		$page = intval( $this->_request->getParam( 'page', 1 ) );
		$parent = intval( $this->_request->getParam( 'p', 0 ) );
		$sort = $this->_request->getParam( 'sort', false );
		$sort_direction = strtolower( $this->_request->getParam( 'sd', false ) );
		
		if( $id > 0 ) {			
			$this->view->id = $id;
			$this->view->sort = $sort;
			$this->view->sort_direction = $sort_direction;
			$this->view->parent = $parent;

			if( !$this->userData ) {
				$pager = $this->_products->getListByProducerWithPagerService( $id, array(
					'r1' => 'yes'
				), false, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit );
			} else {
				$sess = new Zend_Session_Namespace( 'ranks' );
				
				if( count( $sess->data ) > 0 ) {
					$pager = $this->_products->getListByProducerWithPagerService( $id, false, $sess->data, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit );
				} else {
					$pager = $this->_products->getListByProducerWithPagerService( $id, array(
						'r1' => 'yes'
					), false, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit );
				}
			}
			
			$Manufacturers = new Manufacturers();
			
			$manElem = $Manufacturers->getItemService( $id )->getFirst();
			$this->view->man = $manElem;
			
			if( $pager ) {
				$pagerLayout2 = $pager['layout2'];
				$pagerLayout = $pager['layout'];

				$pagerLayout->setTemplate('<a class="nums" href="{%url}">{%page}</a>');
				$pagerLayout->setSelectedTemplate('<a class="nums focus" href="{%url}">{%page}</a>');
				
				$pager = $pager['pager'];
		
				$this->view->list2 = $pagerLayout2->execute();
				$this->view->list = $pagerLayout->execute();
				$this->view->pager = $pagerLayout;
				
				$this->view->result = $pager->getNumResults();
				$this->view->page = $page;
				$this->view->pathInfo = $this->view->baseUrl() . $this->_request->getPathInfo();
				$this->view->limit = $this->itemsLimit;
			
			} else {
				$this->view->emptyResult = true;
			} 

		} else {
			$this->_forward( 'p404', 'index' );
		}
	}
	
	public function tagAction() {
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		$page = intval( $this->_request->getParam( 'page', 1 ) );
		$parent = intval( $this->_request->getParam( 'p', 0 ) );
		$sort = $this->_request->getParam( 'sort', 'price' );
		$sort_direction = strtolower( $this->_request->getParam( 'sd', 'asc' ) );
		
		if( $id > 0 ) {			
			$this->view->id = $id;
			$this->view->sort = $sort;
			$this->view->sort_direction = $sort_direction;
			$this->view->parent = $parent;

			if( !$this->userData ) {
				$pager = $this->_products->getListByTagWithPagerService( $id, array(
					'r1' => 'yes'
				), false, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit );
			} else {
				$sess = new Zend_Session_Namespace( 'ranks' );
				
				if( count( $sess->data ) > 0 ) {
					$pager = $this->_products->getListByTagWithPagerService( $id, false, $sess->data, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit );
				} else {
					$pager = $this->_products->getListByTagWithPagerService( $id, array(
						'r1' => 'yes'
					), false, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit );
				}
			}
			
			if( $pager ) {
			
				$pagerLayout = $pager['layout'];
				$pagerLayout2 = $pager['layout2'];
				$pagerLayout->setTemplate('<a class="nums" href="{%url}">{%page}</a>');
				$pagerLayout->setSelectedTemplate('<a class="nums focus" href="{%url}">{%page}</a>');
				
				$pager = $pager['pager'];
		
				$this->view->list2 = $pagerLayout2->execute();
				$this->view->list = $pagerLayout->execute();
				$this->view->pager = $pagerLayout;
				
				$this->view->result = $pager->getNumResults();
				$this->view->page = $page;
				$this->view->pathInfo = $this->view->baseUrl() . $this->_request->getPathInfo();
				$this->view->limit = $this->itemsLimit;
			
			} else {
				$this->view->emptyResult = true;
			} 

		} else {
			$this->_forward( 'p404', 'index' );
		}
	}

	public function specialAction() {
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		$page = intval( $this->_request->getParam( 'page', 1 ) );
		$parent = intval( $this->_request->getParam( 'p', 0 ) );
		$sort = $this->_request->getParam( 'sort', 'price' );
		$sort_direction = strtolower( $this->_request->getParam( 'sd', 'asc' ) );
		$special = intval( $this->_getParam( 'special', 0 ) );

		if( $special ) {
			if( $id > 0 ) {			
				$this->view->id = $id;
				$this->view->sort = $sort;
				$this->view->sort_direction = $sort_direction;
				$this->view->parent = $parent;

				if( !$this->userData ) {
					$pager = $this->_products->getListSpecialByCategoryWithPagerService( $id, array(
						'r1' => 'yes'
					), false, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit );
					$priceRank = 1;
				} else {
					
					$priceRank = ( $this->userData->price_rank ) ? $this->userData->price_rank : 1;
					
					$pager = $this->_products->getListSpecialByCategoryWithPagerService( $id, array(
						'r' . $priceRank => 'yes'
					), false, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit );
				}
				
				$this->view->priceRank = $priceRank;
				
				if( $pager ) {
	
					$pagerLayout = $pager['layout'];
					$pagerLayout->setTemplate('<a class="nums" href="{%url}">{%page}</a>');
					$pagerLayout->setSelectedTemplate('<a class="nums focus" href="{%url}">{%page}</a>');
					
					$pager = $pager['pager'];
			
					$this->view->list = $pagerLayout->execute();
					$this->view->pager = $pagerLayout;
					
					$this->view->result = $pager->getNumResults();
					$this->view->page = $page;
					$this->view->pathInfo = $this->view->baseUrl() . $this->_request->getPathInfo();
					$this->view->limit = $this->itemsLimit;
				
				} else {
					$this->view->emptyResult = true;
				} 
	
			} else {
				$this->_forward( 'p404', 'index' );
			}
		}
	}
	
	public function showAction() {
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		$page = intval( $this->_request->getParam( 'page', 1 ) );
		$parent = intval( $this->_request->getParam( 'p', 0 ) );
		$sort = $this->_request->getParam( 'sort', 'price' );
		$sort_direction = strtolower( $this->_request->getParam( 'sd', 'asc' ) );
		$special = intval( $this->_getParam( 'special', 0 ) );
		if( $special ) {
			$this->_forward( 'special', 'shop' );
		} else {
			if( $id > 0 ) {			
				$this->view->id = $id;
				$this->view->sort = $sort;
				$this->view->sort_direction = $sort_direction;
				$this->view->parent = $parent;
	
				if( !$this->userData ) {
					$pager = $this->_products->getListByCategoryWithPagerService( $id, array(
						'r1' => 'yes'
					), false, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit );
				} else {
					$sess = new Zend_Session_Namespace( 'ranks' );
					
					if( count( $sess->data ) > 0 ) {
						$pager = $this->_products->getListByCategoryWithPagerService( $id, false, $sess->data, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit );
					} else {
						$pager = $this->_products->getListByCategoryWithPagerService( $id, array(
							'r1' => 'yes'
						), false, $this->locale, $sort, $sort_direction, $this->view->baseUrl(), $page, $this->itemsLimit );
					}
				}
				
				if( $pager ) {
					$pagerLayout2 = $pager['layout2'];
					$pagerLayout = $pager['layout'];

					$pagerLayout->setTemplate('<a class="nums" href="{%url}">{%page}</a>');
					$pagerLayout->setSelectedTemplate('<a class="nums focus" href="{%url}">{%page}</a>');
					
					$pager = $pager['pager'];
			
					$this->view->list2 = $pagerLayout2->execute();
					$this->view->list = $pagerLayout->execute();
					$this->view->pager = $pagerLayout;
					
					$this->view->result = $pager->getNumResults();
					$this->view->page = $page;
					$this->view->pathInfo = $this->view->baseUrl() . $this->_request->getPathInfo();
					$this->view->limit = $this->itemsLimit;
				
				} else {
					$this->view->emptyResult = true;
				} 
			} else {
				$this->_forward( 'p404', 'index' );
			}
		}
	}
	
	public function specialitemAction() {
		$id = intval( $this->_request->getParam( 'id', 0 ) );

		if( $id > 0 ) {
				$LinkProductsSpecial = new LinkProductsSpecial();
				if( !$this->userData ) {
					$item = $this->_products->getItemSpecialService( $id, array(
						'r1' => 'yes'
					) );

					$itemLink = $LinkProductsSpecial->getListByProductService( $id, array(
						'r1' => 'yes'
					) );
					$priceRank = 1;
				} else {
					$priceRank = ( $this->userData->price_rank ) ? $this->userData->price_rank : 1;

					$item = $this->_products->getItemSpecialService( $id, array(
						'r' . $priceRank => 'yes'
					) );
                   
					$itemLink = $LinkProductsSpecial->getListByProductService( $id, array(
						'r' . $priceRank => 'yes'
					) );
				}
				
				if( !isSet( $item->getFirst()->ps_id ) ) {
					$this->_forward( 'p404', 'index' );
				}
				
				$this->view->priceRank = $priceRank;
	
				$CategriesHasProductsSpecial = new CategriesHasProductsSpecial();
				$categories = $CategriesHasProductsSpecial->getByProductService( $id );
				$this->view->categories = $categories;
				
				$this->view->item = $item->getFirst();
				
				$this->view->link = $itemLink;

			} else {
				$this->_forward( 'p404', 'index' );
			}
	}
	
	public function itemAction() {
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		$dim = $this->_request->getParam( 'dim', null );
		
		$special = intval( $this->_getParam( 'special', 0 ) );
		if( $special ) {
			$this->_forward( 'specialitem', 'shop' );
		} else {

			if( $id > 0 ) {
				$this->view->free = is_null( $dim ) ? null : intval( $dim );
				$LinkProducts = new LinkProducts();
				
				if( !$this->userData ) {
					$item = $this->_products->getItemService( $id, array(
						'r1' => 'yes'
					) );
					
					$itemLink = $LinkProducts->getListByProductService( $id, array(
						'r1' => 'yes'
					) );
				} else {
					$sess = new Zend_Session_Namespace( 'ranks' );
					
					if( count( $sess->data ) > 0 ) {
						$item = $this->_products->getItemService( $id, false, $sess->data );
						$itemLink = $LinkProducts->getListByProductService( $id, false, $sess->data );
					} else {
						$item = $this->_products->getItemService( $id, array(
							'r1' => 'yes'
						) );
						$itemLink = $LinkProducts->getListByProductService( $id, array(
							'r1' => 'yes'
						) );
					}
				}
				
				if( !isSet( $item->getFirst()->p_id ) ) {
					$this->_forward( 'p404', 'index' );
				}
	
				$CategriesHasProducts = new CategriesHasProducts();
				$categories = $CategriesHasProducts->getByProductService( $id );
				$this->view->categories = $categories;
				
				$TagsHasProducts = new TagsHasProducts();
				$tags = $TagsHasProducts->getByProductService( $id );
				$this->view->tags = $tags;
				
				$this->view->item = $item->getFirst();
				
				$this->view->link = $itemLink;
			} else {
				$this->_forward( 'p404', 'index' );
			}
		
		}
	}

	public function ratingAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();

		$id = intval( $this->_request->getParam( 'id', 0 ) );
		$rating = floatval( $this->_request->getParam( 'rating', 0 ) );
		$special = floatval( $this->_request->getParam( 'special', 0 ) );

		if( !isSet( $_COOKIE['shop_pr_' . $id] ) ) {
			if( $special ) {
				$item = $this->_products->getItemSpecialForVoteService( $id )->getFirst();
				$iden = 'ps';
			} else {
				$item = $this->_products->getItemForVoteService( $id )->getFirst();
				$iden = 'pr';
			}
			$item->votes_cnt = intval( $item->votes_cnt ) + 1;
			$item->votes_val = intval( $item->votes_val ) + $rating;

			$item->save();
			
			setcookie("shop_" . $iden . "_" . $id, 1, time()+3600*100, "/");
		}
		
		$voteVal = ( $item->votes_val / $item->votes_cnt ) * 2;
		
		$ceilVal = ceil( $voteVal );
		
		$diff = $ceilVal - $voteVal;
		
		$voteVal = ( $diff > 0.5 ) ? floor( $voteVal ) : $ceilVal;

		echo Zend_Json::encode(array(
			'status' => 'OK',
			'value' => $voteVal
		));
	}
	
	public function feedbackAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();

		$from = $this->_request->getParam( 'from', 0 );
		$to = $this->_request->getParam( 'to', 0 );
		$prod = $this->_request->getParam( 'prod', 0 );
		$special = $this->_request->getParam( 'special', 0 );

		if( filter_var( $from, FILTER_VALIDATE_EMAIL ) && filter_var( $to, FILTER_VALIDATE_EMAIL ) ) {
			if( $special ) {
				
				$url = $this->serverName . $this->view->baseUrl() . '/shop/item/id/' . $prod . '/special/1/' . $this->view->Seo( $item['name_' . $this->locale] );
				
				$item = $this->_products->getItemSpecialForVoteService( $prod )->getFirst();
			} else {
				
				$url = $this->serverName . $this->view->baseUrl() . '/shop/item/id/' . $prod . '/' . $this->view->Seo( $item['name_' . $this->locale] );
				
				$item = $this->_products->getItemForVoteService( $prod )->getFirst();
			}

			$mail = new Core_Mail();
			$mail->addTo( $to, $to );
			$mail->setFrom( $from, $from );
			$mail->setSubject( $this->view->translate( 'feedback_topic' ) );
			$mail->setBodyText( strip_tags( $this->view->translate( 'feedback_body' ) ) );
			$mail->setBodyHtml( $this->view->translate( 'feedback_body' ) . ': <a href="' . $url . '">' . $item['name_' . $this->locale] . '</a>' );
			$mail->send();
			
			echo Zend_Json::encode(array(
				'status' => true
			));
		} else {
			echo Zend_Json::encode(array(
				'status' => false
			));
		}

	}
	
	public function backinstockAction() {
		$p_id = intval( $this->_request->getParam( 'id', 0 ) );
		$d_id = intval( $this->_request->getParam( 'dim', 0 ) );
		
		$this->view->p_id = $p_id;
		$this->view->d_id = $d_id;
		
		$add = false;
		
		if( $this->userData ) {
			$add = true;
			$data = array(
				'products_p_id' => $p_id,
				'dimension_d_id' => $d_id,
				'email' => $this->userData->email,
				'add_date' => Date( 'Y-m-d H:i:s' )
			);
		} else {
			$this->view->frm = true;
			
			if( $this->_request->isPost() ) {
			
				$post = $this->_request->getPost();
				
				if( !filter_var( $post['email'], FILTER_VALIDATE_EMAIL ) ) {
					$this->view->error = true;
				} else {
					$add = true;
					$data = array(
						'products_p_id' => $p_id,
						'dimension_d_id' => $d_id,
						'email' => $post['email'],
						'add_date' => Date( 'Y-m-d H:i:s' )
					);
				}
			
			}
		}
		
		if( $add ) {
			$BackInStock = new BackInStock();
			
			foreach( $data as $key => $value ) {
				$BackInStock->{$key} = $value;
			}
			
			$this->view->frm = false;
			
			$BackInStock->save();
			
			$this->view->okcomm = true;
		}
	}
	
	public function wishlistAction() {
		$p_id = intval( $this->_request->getParam( 'id', 0 ) );
		$dem = intval( $this->_request->getParam( 'dem', 0 ) );
		$multi = intval( $this->_request->getParam( 'multi', 0 ) );

		if( $this->userData ) {
			
			$Wishlist = new Wishlist();
			
			if( $multi ) {
				foreach( $this->basket->sess->basket['items'] as $value ) { 
					foreach( $value as $elem ) {

						$item = $Wishlist->getItemService( $elem['info']->p_id, $this->userData->u_id );

						if( !$item->getFirst() ) {
							$Wishlist->products_p_id = $elem['info']->p_id;
							$Wishlist->users_u_id = $this->userData->u_id;
							$Wishlist->add_date = Date( 'Y-m-d H:i:s' );
							$Wishlist->save();
						}

					}
				}
				
				$this->basket->clear();
				
			} else {
				$item = $Wishlist->getItemService( $p_id, $this->userData->u_id );
				
				if( !$item->getFirst() ) {
					$Wishlist->products_p_id	= $p_id;
					$Wishlist->users_u_id = $this->userData->u_id;
					$Wishlist->add_date = Date( 'Y-m-d H:i:s' );
					$Wishlist->save();
	
					$Dimension = new Dimension();
	
					$itemDime = $Dimension->getItemService( $dem );
					if( $first = $itemDime->getFirst() ) {
						$first = $first->toArray();
						if( $first['stock'] < 1 ) {
							$BackInStock = new BackInStock();
							$BackInStock->{'products_p_id'} = $p_id;
							$BackInStock->{'dimension_d_id'} = $dem;
							$BackInStock->{'email'} = $this->userData->email;
							$BackInStock->{'add_date'} = Date( 'Y-m-d H:i:s' );
							$BackInStock->save();
						}
					}
				}
	
				$this->view->wishlist_ok = true;
			
			}
		}
	}
	
	public function observedAction() {
		if( $this->_request->isPost() ) {
			$this->_helper->layout->disableLayout();
			$this->_helper->viewRenderer->setNoRender();
			
			$post = $this->_request->getPost();
			
			$Wishlist = new Wishlist();
			foreach( $post['elem'] as $val ) {
				$Wishlist->deleteItemService( $val, $this->userData->u_id );
			}	
		} else {
		
			$page = intval( $this->_request->getParam( 'page', 1 ) );
	
			$Wishlist = new Wishlist();
	
			$pager = $Wishlist->getListByUserServiceWithPager( 
				$page, 
				$this->view->baseUrl() . '/shop/observed/page/{%page_number}', 
				$this->userData->u_id 
			);
			
			$pagerLayout = $pager['layout'];
			$pagerLayout->setTemplate('<a class="nums" href="{%url}">{%page}</a>');
			$pagerLayout->setSelectedTemplate('<a class="nums focus" href="{%url}">{%page}</a>');
			
			$pager = $pager['pager'];
	
			$this->view->list = $pagerLayout->execute();
			$this->view->pager = $pagerLayout;
			
			$this->view->result = $pager->getNumResults();
			$this->view->page = $page;
			$this->view->pathInfo = $this->view->baseUrl() . $this->_request->getPathInfo();
			$this->view->limit = 12;
		
		}
	}

	public function bonAction() {
		if($this->_request->isPost())
		{
			$post = $this->_request->getPost();
			
			foreach( $post as $key => $value ) {
				$this->view->{$key} = $value;
			}
		
			if($post['dar_email']=='' || !filter_var($post['dar_email'], FILTER_VALIDATE_EMAIL) )
			{
				$this->view->error = 'error_no_mail';
			}
			elseif($post['id_bonu']==0)
			{
				$this->view->error = 'error_no_voulcher';
			}
			else
			{
			    $dar_pass = '';
				$user = new Users();
				$us = $user->getItemByEmailService($post['dar_email']);
				
				if(!$us)
				{
				    $Users = new Users();
    				$Users->role = 1;
    				$Users->state = 0;
    				$Users->registration_date = Date( 'Y-m-d H:i:s' );
    				$Users->pass = md5(time().rand(1,999));
    				$Users->langs_l_id = Doctrine_Core::getTable('Langs')->findOneByIden( $this->locale )->l_id;
    				$Users->email = $post['dar_email'];
    				$Users->save();
    				
				    $us = $user->getItemByEmailService($post['dar_email']);
				}
				
				if($us) 
				{
					$Orders = new Orders();
					
					$vou = new Vouchers();	
					
					$vou->users_u_id = $us->u_id;
					$vou->value_start = $post['id_bonu'];
					$vou->value = $post['id_bonu'];
					$vou->add_date = Date( 'Y-m-d H:i:s' );
					$vou->cur = $this->currency[$this->locale];
					$vou->save();
					 
					$Orders->users_u_id = ( $this->userData ) ? $this->userData->u_id : null;
					$Orders->currency = $this->currency[$this->locale];
					$Orders->price = $post['id_bonu'];
					$Orders->email = $this->userData->email;
					$Orders->state = 0;
					$Orders->state2 = 1;
					$Orders->state3 = 0;
					$Orders->state4 = 0;
					$Orders->state5 = 0;
					$Orders->nip_to_fv = $post['fv_nip'];
					$Orders->company_to_fv = $post['fv_company_name'];
					$Orders->name_to_fv = $post['fv_name'];
					$Orders->surname_to_fv = $post['fv_surname'];
					$Orders->street_to_fv = $post['fv_street'];
					$Orders->nr_home_to_fv = intval($post['fv_nr_home']);
					$Orders->nr_flat_to_fv = intval($post['fv_nr_flat']);
					$Orders->locality_to_fv = $post['fv_locality'];
					$Orders->zip_to_fv = $post['fv_zip'];
					$Orders->province_to_fv = $post['fv_province'];
					$Orders->country_to_fv = $post['fv_country'];
					$Orders->add_date = Date( 'Y-m-d H:i:s' );
					$Orders->vouchers_v_id = $vou->v_id;
					$Orders->vouchers_owner_id = $us->u_id;
					$Orders->save();
					
					
            		//$srcLogo = $this->serverName . $this->view->baseUrl() . '/public/images/carnaubalogo.jpg';
            		$srcLogo = 'public/images/carnaubalogo.jpg';
            		
            		$notaId = date('Y').'/NK/'.$vou->v_id;
            		
            		$html['header'] = '
            		
                      <TABLE  cellpadding="0" cellspacing="0" BORDER="0" style="font-size:12px; width:90%; margin:0 auto">
                         <TBODY>
                         <TR>
                            <TD>
                            <img src="'.$srcLogo.'" width="150" height="115">
                            </TD>
                            <td>
                            ORYGINAŁ / KOPIA
                            </td>
                            <TD style="text-align:right">
                            <b>Kraków '.date("d/m/Y").'</b>
                            </TD>
                         </TR>
                      </TBODY>
                      </TABLE>';
            		
					$html['body'] = '
					
                    <style type="text/css">
                    body, td {font-family: arial; font-size:12px }
                    .bg1 {background-color:#F3F3F3; font-weight:bold}
                    </style>
                    
                    <body>
                    
                      <p style="font-size:20px; width:90%; text-align:left; margin:0 auto">
                      <b>'.$this->view->translate('bon_notaksiegowa').' '.$notaId.'</b><br>
                      <span style="font-size:12px">z dnia '.date("d/m/Y").'</span>
                      </p>
                      
                       <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="font-size:10px; width:90%; text-align:left; margin:15px auto 15px auto">
                         <TBODY>
                         <TR>
                            <TD style="text-align:left; vertical-align:top">
                            	<b>'.$this->view->translate('bon_wystawca').'</b><br>
                    		  	Cars Care Sp. z o.o.<br>
                    		  	ul. Szlak 77/134<br>
                          		31-153 Kraków<br>
                          		Polska<br>
                          		NIP: 676-240-99-08<br>
                            </TD>
                            <td style="text-align:right; vertical-align:top">
                            	<b>'.$this->view->translate('bon_platnik').'</b><br>
                            	<b>'.$this->view->translate('bon_login').':</b> '.$this->userData->email.'<br>
                            	<b>'.$this->view->translate('bon_imienazwisko').':</b> '.$post['fv_name'].' '.$post['fv_surname'].( (!empty($post['fv_company_name'])) ? ' - '.$post['fv_company_name'] : '' ).'<br>
								<b>'.$this->view->translate('bon_adres').':</b> '.$post['fv_street'].' '.$post['fv_nr_home'].'<br>
								<b>'.$this->view->translate('bon_miasto').':</b> '.$post['fv_zip'].' '.$post['fv_locality'].'<br>
                            </td>
                            <td style="text-align:right; vertical-align:top">
                            	<b>'.$this->view->translate('bon_odbiorca').'</b><br>
                            	<b>'.$this->view->translate('bon_login').':</b> '.$us->email.'<br>
                            	<b>'.$this->view->translate('bon_imienazwisko').':</b> '.$us->name.' '.$us->surname.( (!empty($us->company_name)) ? ' - '.$us->company_name : '' ).'<br>
								<b>'.$this->view->translate('bon_adres').':</b>'.$us->street.' '.$us->nr_home.'<br>
								<b>'.$this->view->translate('bon_miasto').':</b> '.$us->zip.' '.$us->locality.'<br>
                            </td>
                         </TR>
                      </TBODY>
                      </TABLE>
                    
                      <div style="width:90%; margin:16px auto; font-weight:bold; font-size:15px; text-align:center">
                      '.$this->view->translate('bon_prosimyozgodne').':</b> 
                      </div>
                      
                      <table border="1" cellpadding="3" cellspacing="0" style="width:60%; margin:10px auto">
                      	<tr>
                      		<td class="bg1" style="text-align:right">'.$this->view->translate('bon_obciazylismy').' (PLN)</td>
                      		<td class="bg1">'.$this->view->translate('bon_tresc').'</td>
                      	</tr>
                      	<tr>
                      		<td style="text-align:right">'.$vou->value.'</td>
                      		<td>'.$this->view->translate('bon_tytulemzakupu').'</td>
                      	</tr>
                      	<tr>
                      		<td style="text-align:right"><b>'.$vou->value.'</b></td>
                      		<td><b>'.$this->view->translate('bon_razem').'</b></td>
                      	</tr>
                      </table>
                      
					  <div style="width:90%; margin:0 auto; text-align:left">
					  '.$this->view->translate('bon_text1').': Alior Bank S.A konto: <b>21 2490 0005 0000 4520 2521 0620</b><br>
					  '.$this->view->translate('bon_text2').': <b>'.$notaId.'</b><Br><br>
					  '.$this->view->translate('bon_text3').' 
					  <Br>
					 </div>
					
                      <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="font-size:12px; width:90%; text-align:center; margin:80px auto 15px auto">
                      <TBODY>
                        <tr>
                          <td style="text-align:left">Kamil Krawczyk</td>
                          <td style="text-align:right"></td>
                        </tr>
                        <tr>
                          <td style="text-align:left"><b>WYSTAWIAJĄCY</b></td>
                          <td style="text-align:right"><b>AKCEPTUJĄCY</b></td>
                        </tr>
                      </TBODY>
                      </TABLE>
					
                      
                      </body>
					
					';
					
                    $html['fotter'] = '
            
                      <TABLE cellpadding="0" cellspacing="0" BORDER="0" style="text-align:center; font-size:10px; width:90%; margin:10px auto 15px auto">
                      <TBODY>
                        <tr>
                          <td style="vertical-align:top">
                            <span style="color:#a50021"><b>'.$this->view->translate('order_renowacja').'  </b></span><br>
                            Cars Care Sp. z o.o.<br>
                            Salon - ul. Balicka 117<br>
                            30-149 Kraków<br>
                          </td>
                          <td style="vertical-align:top">
                            <span style="color:#a50021"><b>'.$this->view->translate('order_pielegnacja').'  </b></span><br>
                            NIP: 676-240-99-08<br>
                            kom +48 501-509-399<br>
                            KRS: 0000345500<br>
                          </td>
                          <td style="vertical-align:top">
                            <span style="color:#a50021"><b>'.$this->view->translate('order_ochrona').'  </b></span><br>
                            www.carnauba.pl<br>
                          </td>
                        </tr>
                      </TBODY>
                      </TABLE>
                      <p style="text-align:right">{PAGENO}</p>';
					
					$filename = 'bon_'.$Orders->o_id.'.pdf';
            	    require_once("./library/mpdf/mpdf.php");
            	    $mpdf=new mPDF('utf-8');
            	    $mpdf->SetHTMLHeader($html['header'], null, true);
            	    $mpdf->SetHTMLFooter($html['fotter']);
            	    $mpdf->WriteHTML($html['body']);
            	    
            	    $contentPdfFile = $mpdf->Output('', 'S');
            	    file_put_contents("./public/faktury/".$filename, $contentPdfFile);
					
					$session = md5(time());
					$session_id = substr($session,0, 7);

					$this->view->nr_order = $Orders->o_id;
					
					$this->view->formplatnosci = true;
					$this->view->error = '<form action="https://www.platnosci.pl/paygw/ISO/NewPayment" method="post" name="payform">';
					$this->view->error .= "<input type='hidden' name='first_name' value=".$post['fv_name']." >";
					$this->view->error .= "<input type='hidden' name='last_name' value=".$post['fv_surname'].">";
					$this->view->error .= "<input type='hidden' name='email' value='".$this->userData->email."'>";
					$this->view->error .= "<input type='hidden' name='pos_id' value='39289'>";
					$this->view->error .= "<input type='hidden' name='pos_auth_key' value='cVQb72R'>";
					$this->view->error .= "<input type='hidden' name='session_id' value=".$session_id.">";
					$this->view->error .= "<input type='hidden' name='amount' value='".$post['id_bonu']."0'>";
					$this->view->error .= "<input type='hidden' name='desc' value='".$this->view->nr_order."'>";
					$this->view->error .= "<input type='hidden' name='desc2' value='".$post['dar_email']."'>";
					$this->view->error .= "<input type='hidden' name='client_ip' value=".$_SERVER['REMOTE_ADDR'].">";
					$this->view->error .= "<input type='image' src='".$this->serverName."/public/images/poprzezplatnosci.jpg' alt='Zapłać poprzez Platnosci.pl' value='Zapłać poprzez Platnosci.pl'>";
					$this->view->error .= "</form>";
				}
				else
					$this->view->error = 'error_no_user';
			}
		}
		else
		{
			if($this->userData){
			     $this->view->fv_nip = $this->userData->nip;
			     $this->view->fv_company_name = $this->userData->company_name;
	             $this->view->fv_name = $this->userData->name;
	             $this->view->fv_surname = $this->userData->surname;
	             $this->view->fv_province = $this->userData->province;
	             $this->view->fv_country = $this->userData->country;
	             $this->view->fv_locality = $this->userData->locality;
	             $this->view->fv_street = $this->userData->street;
	             $this->view->fv_nr_home = $this->userData->nr_home;
	             $this->view->fv_nr_flat = $this->userData->nr_flat;
	             $this->view->fv_zip = $this->userData->zip;
			}
		}
		
	}
}
